<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <view class="component-share-shop-popup shareShopPopup">
    <uni-popup
      ref="sharePopRef"
      :is-mask-click="false"
      class="share-pop"
    >
      <view class="pop-main">
        <view class="shop-name-logo">
          <view class="shop-logo">
            <image
              :src="util.checkFileUrl(shopInfo.shopLogo)"
              style="width: 100%; height: 100%; min-width: 84rpx"
              mode="aspectFill"
            />
          </view>
          <view class="shop-name">
            {{ shopInfo.shopName }}
          </view>
        </view>
        <view class="qr-code">
          <!-- 商家二维码 -->
          <image
            class="code"
            :src="shareWxCode"
          />
        </view>
        <text class="tip-text">
          - 分享店铺给好友 -
        </text>
        <view class="share-item">
          <!-- 暂时只有在公众号才能分享到微信好友与朋友圈 -->
          <!-- #ifdef H5 -->
          <!-- 微信好友 -->
          <view
            v-if="isWechat"
            class="we-chat item"
            @tap="onShareWay(0)"
          >
            <view class="item-image">
              <image
                src="/static/images/we-chat.png"
                style="width: 36rpx; height: 36rpx"
                mode="aspectFit"
              />
            </view>
            <text class="item-text">
              微信好友
            </text>
          </view>
          <!-- 朋友圈 -->
          <view
            v-if="isWechat"
            class="circle-friends item"
            @tap="onShareWay(1)"
          >
            <view class="item-image">
              <image
                src="/static/images/circle-friends.png"
                style="width: 36rpx; height: 30rpx"
                mode="aspectFit"
              />
            </view>
            <text class="item-text">
              朋友圈
            </text>
          </view>
          <!-- #endif -->
          <!-- 复制链接 -->
          <view
            class="copy-link item"
            @tap="copy"
          >
            <view class="item-image">
              <image
                src="/static/images/link.png"
                style="width: 30rpx; height: 30rpx"
                mode="aspectFit"
              />
            </view>
            <text class="item-text">
              复制链接
            </text>
          </view>
          <!-- 保存相册 -->
          <view
            v-if="!isWechat"
            class="save-to-album item"
            @tap="downloadImg"
          >
            <view class="item-image">
              <image
                src="/static/images/download.png"
                style="width: 30rpx; height: 30rpx"
                mode="aspectFit"
              />
            </view>
            <text class="item-text">
              保存相册
            </text>
          </view>
        </view>
      </view>
      <view
        class="pop-close"
        @tap="closeSharePop"
      >
        <image
          src="/static/images/close.png"
          style="width: 18rpx; height: 18rpx"
        />
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { onMounted } from 'vue'
import Qr from '../../utils/wxqrcode.js'
import util from '@/utils/util'

const emit = defineEmits([
  'openGuideShare',
  'openGuideShare',
  'openGuideShare',
  'openGuideShare',
  'closeSharePop'
])
const props = defineProps({
  shopInfo: {
    type: Object,
    default: () => {
      return {}
    }
  },
  isWechat: {
    type: Boolean,
    default: false
  }
})

let userMobileUrl = ''
// 需要保存的图片路径
const shareWxCode = ref('')

onMounted(() => {
  userMobileUrl = import.meta.env.VITE_APP_H5_DOMAIN
  const code = userMobileUrl + 'package-shop/pages/shop-page/shop-page?shopId=' + props.shopInfo.shopId
  shareWxCode.value = Qr.createQrCodeImg(code, { size: 250 })
})

// 复制链接
const copy = () => {
  util.uniCopy({
    content:
      userMobileUrl +
      'package-shop/pages/shop-page/shop-page?shopId=' +
      props.shopInfo.shopId,
    success: (res) => {
      uni.showToast({
        title: res,
        icon: 'none'
      })
    },
    error: (e) => {
      uni.showToast({
        title: e,
        icon: 'none',
        duration: 3000
      })
    }
  })
}

/**
 * 用户点击分享到微信好友或朋友圈
 * @param {number} scene 分享场景 0:微信好友分享，1:朋友圈分享
 */
const onShareWay = (scene) => {
  // #ifdef H5
  // 微信内置浏览器分享到微信
  if (props.isWechat) {
    const sharedata = {
      title: props.shopInfo.shopName, // 分享标题
      imgUrl: util.checkFileUrl(props.shopInfo.shopLogo), // 分享图标
      link:
        userMobileUrl +
        'package-shop/pages/shop-page/shop-page?shopId=' +
        props.shopInfo.shopId, // 分享链接
      desc: scene ? props.shopInfo.intro : '' // 分享描述(朋友圈分享无需desc参数)
    }
    if (scene === 0) {
      closeSharePop()
      emit('openGuideShare')
      // 分享到微信好友
      wechat.callWexinShare(
        sharedata,
        () => {
          closeSharePop()
          emit('openGuideShare')
        }
        // (failMsg) => {
        //   // console.log('shareFailMsg', failMsg)
        // }
      )
    } else {
      closeSharePop()
      emit('openGuideShare')
      // 分享到朋友圈
      wechat.callonCircleFriendsShare(
        sharedata,
        () => {
          closeSharePop()
          emit('openGuideShare')
        }
        // (failMsg) => {
        //   console.log('shareFailMsg', failMsg)
        // }
      )
    }
  }
  // #endif
}

/**
 * 保存图片至相册
 */
const downloadImg = () => {
  // #ifdef H5
  // 非微信内嵌浏览器保存图片
  if (!props.isWechat) {
    const a = document.createElement('a') // 创建a 标签
    a.href = shareWxCode.value // 把图片路径赋到a标签的href上
    a.download = new Date().getTime() // 图片文件名
    // 创建鼠标事件并初始化
    const e = new MouseEvent('click', (true, false, window))
    // 执行保存到本地
    a.dispatchEvent(e)
    if (shareWxCode.value) {
      uni.showToast({
        icon: 'none',
        mask: true,
        title: '保存成功'
      })
      closeSharePop()
    } else {
      uni.showToast({
        icon: 'none',
        mask: true,
        title: '保存失败'
      })
    }
  }
  // #endif

  // #ifndef H5 || MP-WEIXIN || APP-PLUS
  // 非H5进行保存
  uni.saveImageToPhotosAlbum({
    filePath: shareWxCode.value,
    success () {
      uni.showToast({
        icon: 'none',
        mask: true,
        title: '保存成功'
      })
    },
    fail () {
      uni.showToast({
        icon: 'none',
        mask: true,
        title: '保存失败'
      })
    }
  })
  // #endif
  // #ifdef APP-PLUS
  const bitmap = new plus.nativeObj.Bitmap('test')
  bitmap.loadBase64Data(shareWxCode.value, function () {
    const url = '_doc/' + new Date().getTime() + '.png' // url为时间戳命名方式
    bitmap.save(url, {
      overwrite: true // 是否覆盖
      // quality: 'quality'  // 图片清晰度
    }, () => {
      uni.saveImageToPhotosAlbum({
        filePath: url,
        success () {
          uni.showToast({
            title: '图片保存成功',
            icon: 'none'
          })
          bitmap.clear()
        }
      })
    }, () => {
      uni.showToast({
        title: '图片保存失败',
        icon: 'none'
      })
      bitmap.clear()
    })
  }, () => {
    uni.showToast({
      title: '图片保存失败',
      icon: 'none'
    })
    bitmap.clear()
  })
  // #endif
  // #ifdef MP-WEIXIN
  getSaveImg(shareWxCode.value)
  // #endif
}
// 获取授权判断是否授权相册
const getSaveImg = (qrcode) => {
  uni.getSetting({
    success: (res) => {
      if (!res.authSetting['scope.writePhotosAlbum']) {
        uni.showModal({
          title: '警告',
          content: '检测到您没您未授权相册权限,点击确定获取授权。',
          success (res) {
            if (res.confirm) {
              uni.authorize({
                scope: 'scope.writePhotosAlbum',
                success () {
                  // 用户已经同意
                  saveImgToAlbum(qrcode)
                },
                fail () {
                  // console.log('用户拒绝授权相册')
                }
              })
            }
          }
        })
      } else {
        saveImgToAlbum(qrcode)
      }
    }
    // fail: () => {
    //   console.log('点击了拒绝')
    // }
  })
}
// 保存二维码图片到相册
const saveImgToAlbum = (qrcode) => {
  const base64 = qrcode.replace(/^data:image\/\w+;base64,/, '')// 去掉data:image/png;base64,
  const fileManager = uni.getFileSystemManager()
  fileManager.writeFile({
    filePath: wx.env.USER_DATA_PATH + '/img.jpg', // 指定图片的临时路径
    data: base64, // 要写入的文本或二进制数据
    encoding: 'base64', // 指定写入文件的字符编码
    success: () => {
      // console.log('写入文件成功', res)
      // console.log(wx.env.USER_DATA_PATH + '/img.jpg')
      uni.saveImageToPhotosAlbum({ // 保存图片到相册
        filePath: wx.env.USER_DATA_PATH + '/img.jpg',
        success () {
          uni.showToast({
            title: '保存成功'
          })
        }
        // fail (err) {
        //   console.log('保存失败', err)
        // }
      })
    }
    // file: err => {
    //   console.log('写入文件失败', err)
    // }
  })
}

const sharePopRef = ref(null)
// 打开分享弹出框
const openSharePop = () => {
  sharePopRef.value?.open()
}
// 关闭分享弹出框
const closeSharePop = () => {
  emit('closeSharePop', '')
}
defineExpose({
  openSharePop
})

</script>

<style lang="scss" scoped>
@use './share-shop-popup.scss';
</style>
